<template>
  <div class="article-detail-container">
    <div class="article-head">
      <h1>{{detail.name}}</h1>
      <div>作者: <span v-if="detail.author">{{detail.author.name}}</span></div>
      <div>更新于: {{detail.updatedAt | dateTime('ymdhms')}}</div>
    </div>
    
    <client-only>
      <mavon-editor :value="detail.content"
                    :boxShadow="false"
                    :toolbarsFlag="false"
                    :shortCut="false"
                    :subfield="false"
                    defaultOpen="preview"
                    :editable="false"></mavon-editor>
  
      <div class="comment-wrap">
        <p class="title">评论</p>
        <div class="form-box">
          <comment-input :show-avatar="true"
                         :avatar-url="avatarUrl"
                         :editable="isLogin"
                         :data-source="{ articleId: detail._id }"
                         @progress="handleProgress"></comment-input>
        </div>
        
        <a-list
          class="comment-list"
          item-layout="horizontal"
          :data-source="comments"
          size="small"
        >
          <template slot="loadMore">
            <div class="comment-list-footer" v-if="showLoadingMore">
              <a-spin v-if="isLoading" />
              <a-button v-else @click="onLoadMore">
                加载更多
              </a-button>
            </div>
          </template>
          
          <a-list-item slot="renderItem" slot-scope="item, index">
            <a-comment>
              <a-avatar slot="avatar" :src="item.from.avatar" :alt="item.from.name" icon="user" />
              
              <span slot="author">
                {{ item.from.name }}
                <a-tag color="blue" v-if="item.isAuthor">作者</a-tag>
              </span>
              
              <div slot="content">
                <span v-if="item.to">回复 {{ item.to.name }}: </span>
                <span>{{ item.content }}</span>
              </div>
              
              <a-tooltip slot="datetime" :title="item.createdAt | dateTime('ymdhms')">
                <span>{{ item.createdAt | dateTime('ymdhms') }}</span>
              </a-tooltip>
              
              <template slot="actions">
                <span key="comment-basic-like">
                  <a-icon type="like" :theme="item.isLike ? 'filled' : 'outlined'" @click="like(item)" />
                  <span style="cursor: auto">
                    {{ item.likeCount }}
                  </span>
                </span>
                <span key="comment-basic-reply-to" @click="reply(item)">回复</span>
              </template>
  
              <div class="reply-input-box" v-if="item.showReplyBox">
                <comment-input :editable="isLogin"
                               :autofocus="true"
                               :data-source="{ articleId: item.articleId, replyCommentId: item._id, replyUserId: item.from._id }"
                               @progress="handleProgress($event, item)"></comment-input>
              </div>
              
              <template v-if="item.replyComments && item.replyComments.length > 0">
                <a-comment class="reply-comment-list" v-for="(sub, idx) in item.replyComments" :key="idx">
                  <span slot="author">
                    {{ sub.from.name }}
                    <a-tag color="blue" v-if="sub.isAuthor">作者</a-tag>
                  </span>
                  <a-avatar
                    slot="avatar"
                    :src="sub.from.avatar"
                    icon="user"
                    :alt="sub.from.name"
                  />
                  <div slot="content">
                    <span v-if="sub.to">回复 {{ sub.to.name }}: </span>
                    <span>{{ sub.content }}</span>
                  </div>
                  <a-tooltip slot="datetime" :title="sub.createdAt | dateTime('ymdhms')">
                    <span>{{ sub.createdAt | dateTime('ymdhms') }}</span>
                  </a-tooltip>
  
                  <template slot="actions">
                    <span key="comment-basic-like">
                      <a-icon type="like" :theme="sub.isLike ? 'filled' : 'outlined'" @click="like(sub)" />
                      <span style="cursor: auto">
                        {{ sub.likeCount }}
                      </span>
                    </span>
                    <span key="comment-basic-reply-to" @click="reply(sub)">回复</span>
                  </template>
  
                  <div class="reply-input-box" v-if="sub.showReplyBox">
                    <comment-input :editable="isLogin"
                                   :autofocus="true"
                                   :data-source="{ articleId: sub.articleId, replyCommentId: item._id, replyUserId: sub.from._id }"
                                   @progress="handleProgress($event, sub)"></comment-input>
                  </div>
                </a-comment>
              </template>
            </a-comment>
          </a-list-item>
        </a-list>
      </div>
  
      <login-modal-form v-model="visible"></login-modal-form>
    </client-only>
  
  </div>
</template>

<script lang="ts">
  import { Component, Vue, Watch } from 'vue-property-decorator';
  import { Context } from '@nuxt/types';
  import { IArticle } from '@/models/article.model';
  import { ICommentModel } from '@/models/comment.model';
  import { IUserModel } from '~/models/user.model';

  @Component({
    async asyncData({ app, params, error }: Context): Promise<object | void> {
      try {
        const detail = await app.$axios.get<IArticle>(`/blog/article/detail/${params.id}`);
        return { detail };
      } catch (e) {
        error({ statusCode: 500, message: '服务器出错了哦' });
      }
    },
    key(route) {
      return route.fullPath;
    },
  })
  export default class ArticleDetail extends Vue {
    @Watch('$store.state.user.userInfo', { deep: true })
    onWatchUserInfo(newVal: IUserModel): void {
      this.isLogin = !!(newVal && newVal._id);
      this.avatarUrl = this.isLogin ? newVal.avatar : '';
      this.pageIndex = 1;
      this.getComments({ pageIndex: this.pageIndex });
    }
    
    get comments(): ICommentModel[] {
      return this.$store.getters['comment/list'];
    }
    
    get showLoadingMore(): boolean {
      return this.$store.state.comment.hasMore;
    }
    
    readonly detail!: IArticle;
    isLoading: boolean = false;
    avatarUrl: string | undefined = '';
    isLogin: boolean = false;
    visible: boolean = false;

    private pageIndex: number = 1;
    private pageSize: number = 3;
  
    /**
     * 获取评论列表
     * @param criteria
     */
    private getComments(criteria: { pageIndex: number }): void {
      this.isLoading = true;
      const params = {
        articleId: this.detail._id,
        pageIndex: criteria.pageIndex,
        pageSize: this.pageSize,
      };
      this.$store.dispatch('comment/getList', params).then(() => {
        this.isLoading = false;
      });
    }
    
    private created(): void {
      this.isLogin = this.$store.getters['user/loggedIn'];
      if (this.isLogin) {
        this.avatarUrl = this.$store.getters['user/userInfo'].avatar;
      }
    }
  
    private mounted(): void {
      this.getComments({ pageIndex: this.pageIndex });
    }
  
    handleProgress(eventType: string, record?: ICommentModel): void {
      switch (eventType) {
        case 'click':
          this.visible = true;
          break;
        case 'outside':
        case 'save':
          if (record) {
            this.$store.dispatch('comment/updateComment', { ...record, showReplyBox: false });
          }
          break;
      }
    }
    
    /**
     * 点赞
     */
    like(record: ICommentModel): void {
      if (!this.isLogin) {
        this.visible = true;
        return;
      }
      if (record.isLike) {
        return;
      }
      const data = { parentId: record._id, sourceType: 'comment' };
      this.$axios.post('/blog/like/add', data).then(() => {
        const likeCount = (record.likeCount as number) + 1;
        this.$store.dispatch('comment/updateComment', Object.assign({}, record, { likeCount, isLike: true }));
      });
    }
  
    /**
     * 回复
     */
    reply(record: ICommentModel): void {
      if (!this.isLogin) {
        this.visible = true;
        return;
      }
      this.$store.dispatch('comment/updateComment', { ...record, showReplyBox: true });
    }
  
    /**
     * 加载更多评论列表
     */
    onLoadMore(): void {
      if (this.showLoadingMore) {
        this.getComments({ pageIndex: ++this.pageIndex });
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import "../../assets/scss/design/colors";

  .article-detail-container {
    width: 100%;
    background-color: #fff;
    padding: 12px;
    min-height: 100%;
    
    .v-note-wrapper {
      z-index: 2;
    }
  }
  
  .article-head {
    padding-bottom: 12px;
  }
  
  .comment-wrap {
    margin-top: 12px;
    border-top: 1px solid $color-border;
    padding: 12px;
    
    .comment-list {
      padding: 0 12px;
    }
    
    .comment-list-footer {
      text-align: center;
      margin-top: 12px;
      height: 32px;
      line-height: 32px;
    }
    
    & /deep/ .ant-comment {
      width: 100%;
    }
    
    p.title {
      font-size: 18px;
    }
    
    .form-box {
      & /deep/ .ant-comment {
        .ant-comment-inner {
          padding: 0;
        }
      }
    }
  
    .reply-input-box {
      margin-bottom: 12px;
    }
    
    .reply-comment-list {
      padding: 0 12px;
      background-color: $color-border-light;
      
      & /deep/ {
        .ant-comment-content {
          margin: 0 12px;
          padding-bottom: 12px;
          border-bottom: 1px solid $color-border;
        }
        
        .ant-comment-nested {
          padding-bottom: 12px;
          
          .reply-input-box {
            margin-bottom: 0;
            
            .comment-input-comp {
              background-color: #fff;
            }
          }
        }
      }
  
      &:last-child {
        & /deep/ .ant-comment-content {
          border-bottom: none;
        }
      }
    }
  }
</style>
